import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'models/unified_config.dart';
import 'services/config_service.dart';

class BuildConfigPage extends StatefulWidget {
  const BuildConfigPage({super.key});

  @override
  State<BuildConfigPage> createState() => _BuildConfigPageState();
}

class _BuildConfigPageState extends State<BuildConfigPage> {
  late UnifiedConfig _config;
  bool _isLoading = true;
  String _generatedCommand = '';

  @override
  void initState() {
    super.initState();
    _loadConfig();
  }

  Future<void> _loadConfig() async {
    try {
      final configService = await ConfigService.getInstance();
      _config = await configService.loadUnifiedConfig();
      _generateCommand();
      setState(() {
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _config = UnifiedConfig();
        _isLoading = false;
      });
    }
  }

  Future<void> _saveConfig() async {
    try {
      final configService = await ConfigService.getInstance();
      await configService.saveUnifiedConfig(_config);
      _generateCommand();

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('构建配置已保存'),
            backgroundColor: Colors.green,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('保存失败: $e'), backgroundColor: Colors.red),
        );
      }
    }
  }

  void _generateCommand() {
    _generatedCommand = _config.generateNuitkaCommand();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    return Scaffold(
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(24.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 页面标题
            Text(
              '构建配置',
              style: Theme.of(
                context,
              ).textTheme.headlineMedium?.copyWith(fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),
            Text(
              '配置Nuitka的高级构建参数和优化选项',
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: Theme.of(context).colorScheme.onSurfaceVariant,
              ),
            ),
            const SizedBox(height: 32),

            // 优化设置
            Card(
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(
                          Icons.speed,
                          color: Theme.of(context).colorScheme.primary,
                        ),
                        const SizedBox(width: 8),
                        Text(
                          '优化设置',
                          style: Theme.of(context).textTheme.titleMedium
                              ?.copyWith(fontWeight: FontWeight.bold),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    Text('优化级别', style: Theme.of(context).textTheme.titleSmall),
                    const SizedBox(height: 8),
                    Wrap(
                      spacing: 12,
                      children: OptimizationLevel.values.map((level) {
                        return ChoiceChip(
                          label: Text(level.displayName),
                          selected: _config.optimization == level,
                          onSelected: (selected) {
                            if (selected) {
                              setState(() {
                                _config.optimization = level;
                              });
                              _generateCommand();
                            }
                          },
                        );
                      }).toList(),
                    ),
                    const SizedBox(height: 16),
                    SwitchListTile(
                      title: const Text('启用LTO优化'),
                      subtitle: const Text('链接时优化，提高性能但增加编译时间'),
                      value: _config.enableLto,
                      onChanged: (value) {
                        setState(() {
                          _config.enableLto = value;
                        });
                        _generateCommand();
                      },
                    ),
                    SwitchListTile(
                      title: const Text('移除断言'),
                      subtitle: const Text('移除Python断言语句以提高性能'),
                      value: _config.removeAsserts,
                      onChanged: (value) {
                        setState(() {
                          _config.removeAsserts = value;
                        });
                        _generateCommand();
                      },
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 调试设置
            Card(
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(
                          Icons.bug_report,
                          color: Theme.of(context).colorScheme.primary,
                        ),
                        const SizedBox(width: 8),
                        Text(
                          '调试设置',
                          style: Theme.of(context).textTheme.titleMedium
                              ?.copyWith(fontWeight: FontWeight.bold),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    SwitchListTile(
                      title: const Text('启用调试信息'),
                      subtitle: const Text('包含调试符号，便于问题排查'),
                      value: _config.enableDebug,
                      onChanged: (value) {
                        setState(() {
                          _config.enableDebug = value;
                        });
                        _generateCommand();
                      },
                    ),
                    SwitchListTile(
                      title: const Text('显示详细输出'),
                      subtitle: const Text('显示详细的编译过程信息'),
                      value: _config.verbose,
                      onChanged: (value) {
                        setState(() {
                          _config.verbose = value;
                        });
                        _generateCommand();
                      },
                    ),
                    SwitchListTile(
                      title: const Text('显示进度'),
                      subtitle: const Text('显示编译进度条'),
                      value: _config.showProgress,
                      onChanged: (value) {
                        setState(() {
                          _config.showProgress = value;
                        });
                        _generateCommand();
                      },
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 平台设置
            Card(
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(
                          Icons.computer,
                          color: Theme.of(context).colorScheme.primary,
                        ),
                        const SizedBox(width: 8),
                        Text(
                          '平台设置',
                          style: Theme.of(context).textTheme.titleMedium
                              ?.copyWith(fontWeight: FontWeight.bold),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    SwitchListTile(
                      title: const Text('禁用控制台'),
                      subtitle: const Text('创建无控制台窗口的GUI应用'),
                      value: _config.disableConsole,
                      onChanged: (value) {
                        setState(() {
                          _config.disableConsole = value;
                        });
                        _generateCommand();
                      },
                    ),
                    SwitchListTile(
                      title: const Text('启用插件'),
                      subtitle: const Text('自动检测并启用必要的插件'),
                      value: _config.enablePlugins,
                      onChanged: (value) {
                        setState(() {
                          _config.enablePlugins = value;
                        });
                        _generateCommand();
                      },
                    ),
                    SwitchListTile(
                      title: const Text('跟随导入'),
                      subtitle: const Text('自动跟踪和包含所有导入的模块'),
                      value: _config.followImports,
                      onChanged: (value) {
                        setState(() {
                          _config.followImports = value;
                        });
                        _generateCommand();
                      },
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 命令预览
            Card(
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(
                          Icons.terminal,
                          color: Theme.of(context).colorScheme.primary,
                        ),
                        const SizedBox(width: 8),
                        Text(
                          '命令预览',
                          style: Theme.of(context).textTheme.titleMedium
                              ?.copyWith(fontWeight: FontWeight.bold),
                        ),
                        const Spacer(),
                        IconButton(
                          onPressed: () {
                            // 复制命令到剪贴板
                            _copyToClipboard(_generatedCommand);
                          },
                          icon: const Icon(Icons.copy),
                          tooltip: '复制命令',
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    Container(
                      width: double.infinity,
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: Theme.of(context).colorScheme.surfaceVariant,
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(
                          color: Theme.of(context).colorScheme.outline,
                        ),
                      ),
                      child: SelectableText(
                        _generatedCommand.isEmpty
                            ? '请先配置项目基本信息'
                            : _generatedCommand,
                        style: Theme.of(context).textTheme.bodySmall?.copyWith(
                          fontFamily: 'monospace',
                          color: Theme.of(context).colorScheme.onSurfaceVariant,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 32),

            // 保存按钮
            SizedBox(
              width: double.infinity,
              child: FilledButton(
                onPressed: null,
                style: FilledButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                      width: 24,
                      height: 24,
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          colors: [Colors.blue.shade400, Colors.blue.shade600],
                        ),
                        borderRadius: BorderRadius.circular(6),
                      ),
                      child: const Icon(
                        Icons.check_circle,
                        color: Colors.white,
                        size: 16,
                      ),
                    ),
                    const SizedBox(width: 8),
                    const Text('构建配置已自动保存'),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _copyToClipboard(String text) {
    Clipboard.setData(ClipboardData(text: text));
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('命令已复制到剪贴板'),
        duration: Duration(seconds: 2),
      ),
    );
  }
}
